package com.ruoyi.customer.service.impl;

import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.customer.dto.AttachmentInfo;
import com.ruoyi.customer.service.FileUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

/**
 * @Author:zzm
 * @Date: 2025/6/12 11:20
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${ruoyi.profile}")  // 使用 RuoYi 的默认配置
    private String uploadDir;

    // 初始化时检查上传目录
    @PostConstruct
    public void initUploadDir() {
        try {
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
                System.out.println("上传目录已创建: " + uploadPath.toAbsolutePath());
            }
        } catch (IOException e) {
            throw new RuntimeException("无法创建上传目录: " + uploadDir, e);
        }
    }

    @Override
    public AttachmentInfo uploadAttachment(MultipartFile file) throws Exception {
        // 1. 验证文件
        validateFile(file);
        // 2. 生成存储路径
        String originalFilename = file.getOriginalFilename();
        String fileExtension = getFileExtension(originalFilename);
        String storageName = UUID.randomUUID() + "." + fileExtension;
        Path storagePath = Paths.get(uploadDir, storageName);

        // 3. 保存文件
        file.transferTo(storagePath);

        // 4. 构建返回信息
        AttachmentInfo attachment = new AttachmentInfo();
        attachment.setUrl("/profile/" + storageName);  // 使用 RuoYi 默认的资源映射
        attachment.setName(originalFilename);
        attachment.setType(getFileType(fileExtension));
        return attachment;

    }

    private void validateFile(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new Exception("文件不能为空");
        }

        // 文件大小限制 (5MB)
        if (file.getSize() > 60 * 1024 * 1024) {
            throw new Exception("文件大小不能超过60MB");
        }

        // 文件类型检查
        String fileExtension = getFileExtension(file.getOriginalFilename());
        String fileType = getFileType(fileExtension);

        if (!Arrays.asList("image", "pdf", "excel").contains(fileType)) {
            throw new Exception("不支持的文件类型");
        }
    }

    private String getFileExtension(String filename) {
        return filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
    }

    private String getFileType(String extension) {
        if (Arrays.asList("jpg", "jpeg", "png", "gif").contains(extension)) {
            return "image";
        } else if ("pdf".equals(extension)) {
            return "pdf";
        } else if (Arrays.asList("xls", "xlsx").contains(extension)) {
            return "excel";
        }
        return "other";
    }
}
